package com.ebt.m.widget.tablescroll.scroll;

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.ebt.m.R;
import com.ebt.m.utils.NumberHelper;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;


public class RecycleAdapterBenefitList2 extends RecyclerView.Adapter {
    private Context context;
    private ArrayList<RowBenefit> list;
    private ArrayList<Object> mDataArrayList = new ArrayList<Object>();

    private static final int VIEW_TYPE_SECTION = 0;
    private static final int VIEW_TYPE_ITEM = 1;
    private LinkedHashMap<BenefitSection, List<RowBenefit>> mSectionDataMap = new LinkedHashMap<BenefitSection, List<RowBenefit>>();
    private RelativeLayout rl;
    public static final int tablecelltextsize = 12;
    public static final int tablecellwidth = 80;
    public static final int tablecellheight = 50;

    public RecycleAdapterBenefitList2(Context context, ArrayList<RowBenefit> list, RelativeLayout rl) {
        this.context = context;
        this.list = list;
        this.rl = rl;
        new GeneratorDataTask().executeOnExecutor(Executors.newSingleThreadExecutor());
    }

    private void generateSectionMap() {
        if (list.size()>0) {
            int firstAge = list.get(0).getAge();
            int lastAge = list.get(list.size() - 1).getAge();
            int firstGroupId = getGroupId(firstAge);
            int lastGroupId = getGroupId(lastAge);
            int firstIndex = 0;
            int secondIndex = 0;
            for (int i = 0; i < lastGroupId - firstGroupId + 1; i++) {
                int y = list.get(firstIndex).getAge() % 10;
                if (y > 0) y = 10 - y;
                secondIndex = firstIndex + y;
                BenefitSection section = new BenefitSection();
                section.setName(((firstGroupId + i) * 10 + 1) + "—" + ((firstGroupId + i + 1) * 10) + "岁");
                if (i == 0) section.setExpanded(true);
                secondIndex++;
                if (secondIndex > list.size()) {
                    secondIndex = list.size();
                }
                List<RowBenefit> rowBenefits = list.subList(firstIndex, secondIndex);
                mSectionDataMap.put(section, rowBenefits);
                firstIndex = secondIndex;
            }
        }
    }

    public class GeneratorDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            generateSectionMap();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            notifyData();
        }
    }

    private int getGroupId(int age) {
        int i = age / 10;
        int y = age % 10;
        if (y == 0) i--;
        return i;
    }


    public int getCount() {
        return mDataArrayList.size();
    }

    public Object getItem(int location) {
        return mDataArrayList.get(location);
    }

    @Override
    public int getItemViewType(int position) {
        if (mDataArrayList.get(position) instanceof BenefitSection) {
            return VIEW_TYPE_SECTION;
        } else {
            return VIEW_TYPE_ITEM;
        }
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return mDataArrayList.size();
    }


    class OnScrollChangedListenerImp implements HScrollViewWithObserver.OnScrollChangedListener {
        HScrollViewWithObserver mScrollViewArg;

        public OnScrollChangedListenerImp(HScrollViewWithObserver scrollViewar) {
            mScrollViewArg = scrollViewar;
        }

        @Override
        public void onScrollChanged(int l, int t, int oldl, int oldt) {
            mScrollViewArg.smoothScrollTo(l, t);
        }
    }


    public int dip2px(Context context, float dpValue) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return (int) (dpValue * metrics.density + 0.5f);
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = null;
        if (viewType == VIEW_TYPE_ITEM) {
            itemView = LayoutInflater.from(context).inflate(R.layout.layout_table_scroll_item_recycleview, parent, false);
        } else if (viewType == VIEW_TYPE_SECTION) {
            itemView = LayoutInflater.from(context).inflate(R.layout.layout_table_section, parent, false);
        }
        return new BenefitViewHolder(itemView, viewType);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        final BenefitViewHolder viewholder = (BenefitViewHolder) holder;
        int viewType = getItemViewType(position);
        if (viewType == VIEW_TYPE_ITEM) {
            RowBenefit rowBenefit = (RowBenefit) mDataArrayList.get(position);
            viewholder.ll_benifit_titles.removeAllViews();
            int size = rowBenefit.getBenefitsPerAge().size();
            for (int i = 0; i < size; i++) {
                TextView textView1 = new TextView(context);
                textView1.setGravity(Gravity.CENTER);
                textView1.setWidth(dip2px(context, tablecellwidth));
                textView1.setHeight(dip2px(context, RecycleAdapterBenefitList2.tablecellheight));
                textView1.setTextSize(tablecelltextsize);
                textView1.setTextColor(context.getResources().getColor(R.color.table_data_textcolor_modify));
                viewholder.ll_benifit_titles.addView(textView1);

                /** 添加垂直分隔线 **/
                if (i < size - 1) {
                    TextView divlerView = new TextView(context);
                    divlerView.setWidth(dip2px(context, 0.5f));
                    divlerView.setHeight(dip2px(context, RecycleAdapterBenefitList2.tablecellheight));
                    divlerView.setBackgroundColor(context.getResources().getColor(R.color.table_column_divler));
                    viewholder.ll_benifit_titles.addView(divlerView);
                }
            }

            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) viewholder.ll_benifit_titles.getLayoutParams();
            layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
            layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
            viewholder.ll_benifit_titles.setLayoutParams(layoutParams);


            HScrollViewWithObserver headSrcrollView =
                    (HScrollViewWithObserver) rl.findViewById(R.id.hsrollviewTable);
            headSrcrollView.AddOnScrollChangedListener(new OnScrollChangedListenerImp(viewholder.hsrollviewTable));
            final Pair<Integer, Integer> pair = headSrcrollView.mScrollViewObserver.pair;
            if (pair != null) {
                viewholder.hsrollviewTable.post(new Runnable() {
                    @Override
                    public void run() {
                        viewholder.hsrollviewTable.smoothScrollTo(pair.first, pair.second);

                    }
                });
            }


            viewholder.tvRowAge.setTextColor(context.getResources().getColor(R.color.table_data_textcolor_modify));
            viewholder.tvRowAge.setText(rowBenefit.getAge() + "");
            List<Double> benefitsPerAge = rowBenefit.getBenefitsPerAge();
            for (int i = 0; i < size; i++) {
                String money = NumberHelper.formatMoney(benefitsPerAge.get(i));
                TextView tvMoney = (TextView) viewholder.ll_benifit_titles.getChildAt(i * 2);
                tvMoney.setText(money);
            }
        } else if (viewType == VIEW_TYPE_SECTION) {
            final BenefitSection section = (BenefitSection) mDataArrayList.get(position);
            ((BenefitViewHolder) holder).section_name.setText(section.getName());
            ((BenefitViewHolder) holder).section_toggle.setOnCheckedChangeListener(null);
            ((BenefitViewHolder) holder).section_toggle.setChecked(section.isExpanded());
            ((BenefitViewHolder) holder).toggleView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((BenefitViewHolder) holder).section_toggle.toggle();
                }
            });
            ((BenefitViewHolder) holder).section_toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    section.setExpanded(b);
                    notifyData();
                }
            });
        }
    }

    public void notifyData() {
        generateDataList();
        this.notifyDataSetChanged();
    }

    public class BenefitViewHolder extends RecyclerView.ViewHolder {
        TextView section_name;
        View toggleView;
        ToggleButton section_toggle;
        TextView tvRowAge;
        LinearLayout ll_benifit_titles;
        HScrollViewWithObserver hsrollviewTable;

        public BenefitViewHolder(View itemView, int viewType) {
            super(itemView);
            if (viewType == VIEW_TYPE_ITEM) {
                tvRowAge = (TextView) itemView.findViewById(R.id.tvRowAge);
                hsrollviewTable = (HScrollViewWithObserver) itemView.findViewById(R.id.hsrollviewTable);
                ll_benifit_titles = (LinearLayout) itemView.findViewById(R.id.ll_benifit_titles);
            } else if (viewType == VIEW_TYPE_SECTION) {
                section_name = (TextView) itemView.findViewById(R.id.section_tv);
                toggleView = itemView.findViewById(R.id.toggle_view);
                section_toggle = (ToggleButton) itemView.findViewById(R.id.toggle_bt);
            }
        }
    }

    private void generateDataList() {
        mDataArrayList.clear();
        for (Map.Entry<BenefitSection, List<RowBenefit>> entry : mSectionDataMap.entrySet()) {
            BenefitSection key;
            mDataArrayList.add((key = entry.getKey()));
            if (key.isExpanded()) {
                mDataArrayList.addAll(entry.getValue());
            }
        }

    }
}
